package com.lagou.edu.factory;

import com.lagou.edu.annotition.MyAutowired;
import com.lagou.edu.annotition.MyComponent;
import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

@MyComponent("proxyFactory")
public class ProxyFactory {

	@MyAutowired
	private TransactionManager transactionManager;

	/**
	 * Jdk动态代理
	 *
	 * @param obj 委托对象
	 * @return 代理对象
	 */
	public Object getJdkProxy(Object obj) {
		//获取代理方法
		JdkProxy jdkProxy = new JdkProxy(obj, transactionManager);

		//获取代理对象
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), jdkProxy);
	}


	/**
	 * 使用cglib动态代理生成代理对象
	 *
	 * @param obj 委托对象
	 * @return
	 */
	public Object getCglibProxy(Object obj) {
		//获取代理方法
		CglibProxy cglibProxy = new CglibProxy(obj, transactionManager);

		//获取代理对象
		return Enhancer.create(obj.getClass(), cglibProxy);
	}
}
